package com.faintlight.dto;

import com.faintlight.model.KindnessChain;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.stream.Collectors;

@Data
public class ChainDTO {
    private static final Logger logger = LoggerFactory.getLogger(ChainDTO.class);

    private Long id;
    private Long sourceCapsuleId;
    private List<NodeDTO> nodes;
    private boolean completed;
    private String progressText;

    @Data
    public static class NodeDTO {
        private String nickname;
        private String message;
        private int sequence;
    }

    public static ChainDTO fromEntity(KindnessChain chain) {
        logger.debug("🔄 转换传递链实体为 DTO: ID={}, 节点数={}", chain.getId(), chain.getNodes().size());
        ChainDTO dto = new ChainDTO();
        dto.setId(chain.getId());
        dto.setSourceCapsuleId(chain.getSourceCapsule().getId());
        dto.setCompleted(chain.isCompleted());
        
        dto.setNodes(chain.getNodes().stream()
            .sorted((n1, n2) -> Integer.compare(n1.getSequence(), n2.getSequence()))
            .map(node -> {
                NodeDTO nodeDTO = new NodeDTO();
                nodeDTO.setNickname(node.getParticipant().getNickname());
                nodeDTO.setMessage(node.getMessage());
                nodeDTO.setSequence(node.getSequence());
                logger.debug("📌 节点: 序号={}, 用户={}, 消息={}", nodeDTO.getSequence(), nodeDTO.getNickname(), nodeDTO.getMessage());
                return nodeDTO;
            })
            .collect(Collectors.toList()));
        
        int progress = chain.getNodes().size();
        if (progress == 0) {
            dto.setProgressText("温暖进度：0℃ · 等你开启");
        } else if (progress < 3) {
            dto.setProgressText(String.format("温暖进度：%d℃ · 刚开始暖", 28 + progress * 5));
        } else {
            dto.setProgressText(String.format("差你一步就圆满了！当前温度：%d℃", 40 + progress * 3));
        }
        logger.debug("📊 进度文本: {}", dto.getProgressText());
        
        return dto;
    }
}
